package com.hk.Mgr.web.controller.pay;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.PushPayload.Builder;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.Notification;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.web.bind.annotation.*;

import com.hk.commons.StringHelper;
import com.hk.commons.utils.sys.JGPushUtils;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * Description:
 * Company:HK
 * author: Sam
 * date:  2016/11/17 18:01
 */

@RestController
//@RequestMapping(value = "/dd")
//@ConfigurationProperties(prefix = "jpush")
public class bb {

    private static Logger logger = LoggerFactory.getLogger(bb.class);

//    private String apiKey;
//
//    private String masterSecret;


    //jpush/sendMsg
    @ResponseBody
    @RequestMapping(value = "/ddd", method = RequestMethod.GET)
    public void jgPushMsg(@RequestParam String msg,
                          String platForm, // aliases,tags,registIds多个的话以逗号隔开。
                          String aliases, String tags, String registIds, String menu,
                          HttpServletResponse response) throws IOException {
        logger.info("极光推送msg={},platForm={},aliases={},tags={},registIds={}",
                msg, platForm, aliases, tags, registIds);

        Map<String, String> extrasMap = new HashMap<>();

       // JPushClient jpushClient = new JPushClient(masterSecret, apiKey);
        if(StringUtils.isNotEmpty(menu))
            extrasMap.put("pushMenu", menu);
        PushPayload payload = buildPushObject_alert(msg, platForm, aliases,
                tags, registIds, extrasMap);
        try {
            PushResult result = JGPushUtils.jpushClient.sendPush(payload);
            logger.info("Got result - " + result);
            response.setCharacterEncoding("utf-8");
            response.getWriter().write("{\"success\":true }");
            response.getWriter().flush();
        } catch (APIConnectionException e) {
            logger.error("Connection error, should retry later", e);

        } catch (APIRequestException e) {
            logger.error("Should review the error, and fix the request", e);
            logger.info("HTTP Status: " + e.getStatus());
            logger.info("Error Code: " + e.getErrorCode());
            logger.info("Error Message: " + e.getErrorMessage());
        }
    }

    // 所有平台，推送目标是别名为 "alias1"，通知内容为 ALERT。
    private PushPayload buildPushObject_alert(String ALERT, String platForm,
                                              String aliases, String tags, String registIds,
                                              Map<String, String> extrasMap) {
        Builder builder = PushPayload.newBuilder();

        if(StringHelper.isNotEmpty(platForm))
	        switch (platForm) {
	        case "android":
	            builder.setPlatform(Platform.android());
	            if(!extrasMap.isEmpty()){
	            	builder.setNotification(Notification.android(ALERT, null,
                            extrasMap));
	            }
	            break;
	        case "ios":
	            builder.setPlatform(Platform.ios());
	            if(!extrasMap.isEmpty()){
	            	 builder.setNotification(Notification.ios(ALERT, extrasMap));
	            }
	            break;
	        default:
	            builder.setPlatform(Platform.all());
	            builder.setNotification(Notification.alert(ALERT));
	            break;
        }else{
            builder.setPlatform(Platform.all());
            builder.setNotification(Notification.alert(ALERT));
            
        }
        boolean targetAudience = false;
        if (StringUtils.isNotEmpty(aliases)) {
            builder.setAudience(Audience.newBuilder()
                    .addAudienceTarget(AudienceTarget.alias(aliases)).build());
            targetAudience = true;
        }

        if (StringUtils.isNotEmpty(tags)) {
            builder.setAudience(Audience.newBuilder()
                    .addAudienceTarget(AudienceTarget.tag(tags)).build());
            targetAudience = true;
        }
        if (StringUtils.isNotEmpty(registIds)) {
            builder.setAudience(Audience
                    .newBuilder()
                    .addAudienceTarget(AudienceTarget.registrationId(registIds))
                    .build());
            targetAudience = true;
        }
        if (!targetAudience) {
            builder.setAudience(Audience.all());
        }
    return builder.build();
}

    /*
     * 构建推送对象：平台是 Andorid 与 iOS，推送目标是 （"tag1" 与 "tag2" 的并集）且（"alias1" 与 "alias2"
     * 的并集），推送内容是 - 内容为 MSG_CONTENT 的消息，并且附加字段 from = JPush。
     */
    public PushPayload buildPushObject_ios_audienceMore_messageWithExtras(
            String MSG_CONTENT) {
        return PushPayload
                .newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(
                        Audience.newBuilder()
                                .addAudienceTarget(
                                        AudienceTarget.tag("tag1", "tag2"))
                                .addAudienceTarget(
                                        AudienceTarget
                                                .alias("alias1", "alias2"))
                                .build())
                .setMessage(
                        Message.newBuilder().setMsgContent(MSG_CONTENT)
                                .addExtra("from", "JPush").build()).build();
    }


//    public String getApiKey() {
//        return apiKey;
//    }
//
//    public String getMasterSecret() {
//        return masterSecret;
//    }
//
//    public void setApiKey(String apiKey) {
//        this.apiKey = apiKey;
//    }
//
//    public void setMasterSecret(String masterSecret) {
//        this.masterSecret = masterSecret;
//    }
}
